package com.itheima.controller;

import com.itheima.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/upload")
public class UpLoadController {

    @Value("${reggie.path}")
    private String basePath;

    @Autowired
    private HttpServletResponse response;

    @PostMapping("native.do")
    public Result upload(MultipartFile imgFile) throws IOException {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(imgFile.toString());

        //原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        //切割后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + substring;

        File file1 = new File(basePath);

        //文件夹不存在就创建一和文件夹
        if (!file1.exists()) {
            file1.mkdirs();
        }
        imgFile.transferTo(new File(basePath + newFileName));

        return new Result(0,true,"图片上传成功",newFileName);
    }

    @GetMapping("download.do")
    public void downLoad(String name) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(basePath + name);

        ServletOutputStream outputStream = response.getOutputStream();

        byte[] bytes = new byte[1024];
        while (true) {
            int read = fileInputStream.read(bytes);
            if (read == -1) {
                break;
            }
            outputStream.write(bytes, 0, read);
            outputStream.flush();
        }

        outputStream.close();
        fileInputStream.close();
    }
}
